<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="iOS," />





  <link rel="alternate" href="/atom.xml" title="Bingo's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言网络层是 APP 架构的一个重要部分，苹果的 CFNetwork 框架极其难用，导致基于 CFN 的框架 ASI 已经放弃维护。后来苹果推出了 NSURLSession，许多开源的框架都是基于它进行封装，例如我选用的 AFNetworking，运行效率没有 ASI 高，使用比 ASI 简单。但是，从使用的角度来看，还需要继续封装。于是，我依赖于 AFN + YYCache + MJExtens">
<meta name="keywords" content="iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="DKNetworking 网络层框架">
<meta property="og:url" content="https://bingozb.github.io/35.html">
<meta property="og:site_name" content="Bingo's Blog">
<meta property="og:description" content="前言网络层是 APP 架构的一个重要部分，苹果的 CFNetwork 框架极其难用，导致基于 CFN 的框架 ASI 已经放弃维护。后来苹果推出了 NSURLSession，许多开源的框架都是基于它进行封装，例如我选用的 AFNetworking，运行效率没有 ASI 高，使用比 ASI 简单。但是，从使用的角度来看，还需要继续封装。于是，我依赖于 AFN + YYCache + MJExtens">
<meta property="og:updated_time" content="2017-09-04T19:06:15.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="DKNetworking 网络层框架">
<meta name="twitter:description" content="前言网络层是 APP 架构的一个重要部分，苹果的 CFNetwork 框架极其难用，导致基于 CFN 的框架 ASI 已经放弃维护。后来苹果推出了 NSURLSession，许多开源的框架都是基于它进行封装，例如我选用的 AFNetworking，运行效率没有 ASI 高，使用比 ASI 简单。但是，从使用的角度来看，还需要继续封装。于是，我依赖于 AFN + YYCache + MJExtens">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: 'JE30EVH7NI',
      apiKey: '862bb3deb9a3166ed99de0be6527f59c',
      indexName: 'blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于「 ${query} 」的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://bingozb.github.io/35.html"/>





  <title>DKNetworking 网络层框架 | Bingo's Blog</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c8a59b9753bce3ec58f81c89e2acce96";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Bingo's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry, Stay Foolish.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://bingozb.github.io/35.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Bingo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Bingo's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                DKNetworking 网络层框架
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-19T16:39:47+08:00">
                2017-03-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/DKKIT/" itemprop="url" rel="index">
                    <span itemprop="name">DKKIT</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/35.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="35.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/35.html" class="leancloud_visitors" data-flag-title="DKNetworking 网络层框架">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>网络层是 APP 架构的一个重要部分，苹果的 CFNetwork 框架极其难用，导致基于 CFN 的框架 ASI 已经放弃维护。后来苹果推出了 NSURLSession，许多开源的框架都是基于它进行封装，例如我选用的 AFNetworking，运行效率没有 ASI 高，使用比 ASI 简单。但是，从使用的角度来看，还需要继续封装。于是，我依赖于 AFN + YYCache + MJExtension 封装出了 <a href="https://github.com/bingozb/DKNetworking/" target="_blank" rel="external">DKNetworking</a> 框架。</p>
<a id="more"></a>
<h2 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h2><ul>
<li><p>DKNetworkSessionManager 对 AFHTTPSessionManager 进行封装，以便以后可以轻易换掉依赖的 AFN。封装一层底层方法，包括网络请求、文件上传、文件下载这三个方法。其中网络请求调用了 AFN 的私有 API，把 GET、POST、PUT、DELETE、PATCH 这五个方法封成了一个 request 方法。</p>
</li>
<li><p>拥有 AFN 大部分常用功能，包括网络状态监听等，提供类方法和实例方法调用。</p>
</li>
<li><p>根据 JavaWeb 中 HttpServlet 的设计思想，把网络请求的回调封装成了 request 和 response 两个对象。</p>
</li>
<li><p>支持界面多级缓存。</p>
</li>
<li><p>支持链式调用。</p>
</li>
<li><p>支持配合 RAC 框架使用链式调用，支持自定义信号的返回值。</p>
</li>
</ul>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><h3 id="支持-Cocoapods-安装"><a href="#支持-Cocoapods-安装" class="headerlink" title="支持 Cocoapods 安装"></a>支持 Cocoapods 安装</h3><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">pod 'DKNetworking'</div></pre></td></tr></table></figure>
<h3 id="或者下载-Demo-项目"><a href="#或者下载-Demo-项目" class="headerlink" title="或者下载 Demo 项目"></a>或者下载 Demo 项目</h3><ul>
<li><p>将根目录下的 DKNetworking 和 Vendor 文件夹拉进项目，其中 Vendor 文件夹有 AFNetworking、MJExtension、YYCache 和 ReactiveCocoa，前三个是必须依赖的，ReactiveCocoa 是可选的。</p>
</li>
<li><p>必须在 Target -&gt; Build Phases -&gt; Link Binary With Libraries 中添加 <code>libsqlite3.0.tbd</code>，这是 YYCache 框架所需的。</p>
</li>
</ul>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><p>绝大部分方法都可以直接看 DKNetworking.h 中的声明以及注释。</p>
<h3 id="获取单例对象"><a href="#获取单例对象" class="headerlink" title="获取单例对象"></a>获取单例对象</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">DKNetworking *networking = [DKNetworking networkManager];</div></pre></td></tr></table></figure>
<p>从 1.1.0 版本开始提供了一个单例对象宏 <code>DKNetworkManager</code>。</p>
<h3 id="DKN-配置"><a href="#DKN-配置" class="headerlink" title="DKN 配置"></a>DKN 配置</h3><h4 id="设置请求根路径"><a href="#设置请求根路径" class="headerlink" title="设置请求根路径"></a>设置请求根路径</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[DKNetworking setupBaseURL:<span class="string">@"https://m.sfddj.com/app/v1/"</span>];</div></pre></td></tr></table></figure>
<p>baseURL 的路径一定要有“/”结尾，设置后所有的网络访问都使用相对路径。</p>
<h4 id="设置日志"><a href="#设置日志" class="headerlink" title="设置日志"></a>设置日志</h4><h5 id="开启日志打印"><a href="#开启日志打印" class="headerlink" title="开启日志打印"></a>开启日志打印</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[DKNetworking openLog];</div></pre></td></tr></table></figure>
<h5 id="关闭日志打印"><a href="#关闭日志打印" class="headerlink" title="关闭日志打印"></a>关闭日志打印</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[DKNetworking closeLog];</div></pre></td></tr></table></figure>
<h4 id="设置缓存"><a href="#设置缓存" class="headerlink" title="设置缓存"></a>设置缓存</h4><h5 id="设置缓存方式"><a href="#设置缓存方式" class="headerlink" title="设置缓存方式"></a>设置缓存方式</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 设置缓存方式</div><div class="line"> DKNetworkCacheTypeNetworkOnly : 只加载网络数据</div><div class="line"> DKNetworkCacheTypeCacheNetwork : 先加载缓存,然后加载网络</div><div class="line"> @param cacheType 缓存类型</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)setupCacheType:(DKNetworkCacheType)cacheType;</div></pre></td></tr></table></figure>
<h5 id="获取缓存大小"><a href="#获取缓存大小" class="headerlink" title="获取缓存大小"></a>获取缓存大小</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 获取网络缓存的总大小 动态单位(GB,MB,KB,B)</div><div class="line"></div><div class="line"> @return 网络缓存的总大小</div><div class="line"> */</div><div class="line">+ (<span class="built_in">NSString</span> *)cacheSize;</div></pre></td></tr></table></figure>
<h5 id="清除缓存"><a href="#清除缓存" class="headerlink" title="清除缓存"></a>清除缓存</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[DKNetworkCache clearCache];</div></pre></td></tr></table></figure>
<h4 id="设置序列化格式"><a href="#设置序列化格式" class="headerlink" title="设置序列化格式"></a>设置序列化格式</h4><h5 id="设置请求序列化格式"><a href="#设置请求序列化格式" class="headerlink" title="设置请求序列化格式"></a>设置请求序列化格式</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 设置网络请求参数的格式 : 默认为二进制格式</div><div class="line"></div><div class="line"> @param requestSerializer DKRequestSerializerJSON:JSON格式, DKRequestSerializerHTTP:二进制格式</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)setRequestSerializer:(DKRequestSerializer)requestSerializer;</div></pre></td></tr></table></figure>
<h5 id="设置响应反序列化格式"><a href="#设置响应反序列化格式" class="headerlink" title="设置响应反序列化格式"></a>设置响应反序列化格式</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 设置服务器响应数据格式 : 默认为JSON格式</div><div class="line"></div><div class="line"> @param responseSerializer DKResponseSerializerJSON:JSON格式, DKResponseSerializerHTTP:二进制格式</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)setResponseSerializer:(DKResponseSerializer)responseSerializer;</div></pre></td></tr></table></figure>
<h4 id="设置请求超时时间"><a href="#设置请求超时时间" class="headerlink" title="设置请求超时时间"></a>设置请求超时时间</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 设置请求超时时间 : 默认10秒</div><div class="line"></div><div class="line"> @param time 请求超时时长(秒)</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)setRequestTimeoutInterval:(<span class="built_in">NSTimeInterval</span>)time;</div></pre></td></tr></table></figure>
<h4 id="设置-Header"><a href="#设置-Header" class="headerlink" title="设置 Header"></a>设置 Header</h4><h5 id="设置一对请求头参数"><a href="#设置一对请求头参数" class="headerlink" title="设置一对请求头参数"></a>设置一对请求头参数</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 设置一对请求头参数</div><div class="line"></div><div class="line"> @param value 请求头参数值</div><div class="line"> @param field 请求头参数名</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)setValue:(<span class="built_in">NSString</span> *)value forHTTPHeaderField:(<span class="built_in">NSString</span> *)field;</div></pre></td></tr></table></figure>
<h5 id="设置多对请求头参数"><a href="#设置多对请求头参数" class="headerlink" title="设置多对请求头参数"></a>设置多对请求头参数</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 设置多对请求头参数</div><div class="line"></div><div class="line"> @param networkHeader 请求头参数字典</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)setNetworkHeader:(<span class="built_in">NSDictionary</span> *)networkHeader;</div></pre></td></tr></table></figure>
<h3 id="网络状态"><a href="#网络状态" class="headerlink" title="网络状态"></a>网络状态</h3><h4 id="监听网络状态"><a href="#监听网络状态" class="headerlink" title="监听网络状态"></a>监听网络状态</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">[DKNetworking networkStatusWithBlock:^(DKNetworkStatus status) &#123;</div><div class="line">    <span class="keyword">switch</span> (status) &#123;</div><div class="line">        <span class="keyword">case</span> DKNetworkStatusUnknown: <span class="comment">// 网络状态未知</span></div><div class="line">            <span class="keyword">break</span>;</div><div class="line">        <span class="keyword">case</span> DKNetworkStatusNotReachable: <span class="comment">// 无网络</span></div><div class="line">            <span class="keyword">break</span>;</div><div class="line">        <span class="keyword">case</span> DKNetworkStatusReachableViaWWAN: <span class="comment">// 手机网络（蜂窝）</span></div><div class="line">            <span class="keyword">break</span>;</div><div class="line">        <span class="keyword">case</span> DKNetworkStatusReachableViaWiFi: <span class="comment">// WIFI网络</span></div><div class="line">            <span class="keyword">break</span>;</div><div class="line">    &#125;</div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<h4 id="获取当前网络状态"><a href="#获取当前网络状态" class="headerlink" title="获取当前网络状态"></a>获取当前网络状态</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 有网络:YES, 无网络:NO</div><div class="line"> */</div><div class="line">+ (<span class="built_in">BOOL</span>)isNetworking;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> 手机网络:YES, 非手机网络:NO</div><div class="line"> */</div><div class="line">+ (<span class="built_in">BOOL</span>)isWWANNetwork;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> WiFi网络:YES, 非WiFi网络:NO</div><div class="line"> */</div><div class="line">+ (<span class="built_in">BOOL</span>)isWiFiNetwork;</div></pre></td></tr></table></figure>
<h3 id="网络请求"><a href="#网络请求" class="headerlink" title="网络请求"></a>网络请求</h3><h4 id="常规调用"><a href="#常规调用" class="headerlink" title="常规调用"></a>常规调用</h4><p><strong>以 POST 方法为例，方法定义：</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> POST请求</div><div class="line"> </div><div class="line"> @param URL 请求地址</div><div class="line"> @param parameters 请求参数</div><div class="line"> @param callback 请求回调</div><div class="line"> @return 返回的对象可取消请求,调用cancel方法</div><div class="line"> */</div><div class="line">+ (<span class="built_in">NSURLSessionTask</span> *)POST:(<span class="built_in">NSString</span> *)URL parameters:(<span class="built_in">NSDictionary</span> *)parameters callback:(DKNetworkBlock)callback;</div><div class="line">- (<span class="built_in">NSURLSessionTask</span> *)POST:(<span class="built_in">NSString</span> *)URL parameters:(<span class="built_in">NSDictionary</span> *)parameters callback:(DKNetworkBlock)callback;</div></pre></td></tr></table></figure>
<p><strong>调用：</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">[DKNetworking POST:url parameters:@&#123;<span class="string">@"name"</span>:<span class="string">@"bingo"</span>&#125; callback:^(DKNetworkRequest *request, DKNetworkResponse *response) &#123;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<h4 id="链式调用"><a href="#链式调用" class="headerlink" title="链式调用"></a>链式调用</h4><p><strong>方法定义：</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/** 链式调用 */</span></div><div class="line">- (DKNetworking *(^)(<span class="built_in">NSString</span> *url))get;</div><div class="line">- (DKNetworking *(^)(<span class="built_in">NSString</span> *url))post;</div><div class="line">- (DKNetworking *(^)(<span class="built_in">NSString</span> *url))put;</div><div class="line">- (DKNetworking *(^)(<span class="built_in">NSString</span> *url))delete;</div><div class="line">- (DKNetworking *(^)(<span class="built_in">NSString</span> *url))patch;</div><div class="line">- (DKNetworking *(^)(<span class="built_in">NSDictionary</span> *params))params;</div><div class="line">- (DKNetworking *(^)(<span class="built_in">NSDictionary</span> *header))header;</div><div class="line">- (DKNetworking *(^)(DKNetworkCacheType cacheType))cacheType;</div><div class="line">- (DKNetworking *(^)(DKRequestSerializer requestSerializer))requestSerializer;</div><div class="line">- (DKNetworking *(^)(DKResponseSerializer responseSerializer))responseSerializer;</div><div class="line">- (DKNetworking *(^)(DKRequestTimeoutInterval requestTimeoutInterval))requestTimeoutInterval;</div><div class="line">- (<span class="keyword">void</span>(^)(DKNetworkBlock networkBlock))callback;</div></pre></td></tr></table></figure>
<p><strong>调用：</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">DKNetworkManager.post(url).params(@&#123;<span class="string">@"name"</span>:<span class="string">@"bingo"</span>&#125;).callback(^(DKNetworkRequest *request, DKNetworkResponse *response) &#123;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<h4 id="RAC-链式调用"><a href="#RAC-链式调用" class="headerlink" title="RAC 链式调用"></a>RAC 链式调用</h4><p><strong>方法定义：</strong></p>
<p>在原链式方法的基础上补充了一个 executeSignal 方法，返回信号。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#ifdef RAC</span></div><div class="line"><span class="comment">/** RAC链式发送请求 */</span></div><div class="line">- (RACSignal *)executeSignal;</div><div class="line"><span class="meta">#endif</span></div></pre></td></tr></table></figure>
<p><strong>调用：</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">[DKNetworkManager.post(url).params(@&#123;<span class="string">@"name"</span>:<span class="string">@"bingo"</span>&#125;).executeSignal subscribeNext:^(RACTuple *x) &#123;</div><div class="line">    DKNetworkResponse *response = x.second;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125; error:^(<span class="built_in">NSError</span> *error) &#123;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<h4 id="RAC-链式调用-自定义信号的返回值"><a href="#RAC-链式调用-自定义信号的返回值" class="headerlink" title="RAC 链式调用 自定义信号的返回值"></a>RAC 链式调用 自定义信号的返回值</h4><p><strong>方法定义：</strong></p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#ifdef RAC</span></div><div class="line"><span class="comment">/**</span></div><div class="line"> 设置响应结果回调，可以设置信号返回的value为自己想要的值，比如用MJExtension框架，将DKNetworkResponse对象的rawData字典转为自己项目的实体类再返回</div><div class="line"> </div><div class="line"> @param flattenMapBlock 结果映射的设置回调block，其中RACTuple的first为DKNetworkRequest对象，second为DKNetworkResponse对象</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)setupResponseSignalWithFlattenMapBlock:(DKNetworkFlattenMapBlock)flattenMapBlock;</div><div class="line"><span class="meta">#endif</span></div></pre></td></tr></table></figure>
<p><strong>使用：</strong></p>
<p>考虑到代码执行顺序的问题，建议在项目中创建一个继承自 NSObject 的类 DKNetworkConfig，在 + load 方法中调用 DKN 的配置方法，设置回调的信号的 return 值，根据不同项目进行配置。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">[DKNetworking setupResponseSignalWithFlattenMapBlock:^RACStream *(RACTuple *tuple) &#123;</div><div class="line">    DKNetworkResponse *response = tuple.second; <span class="comment">// 框架默认返回的response</span></div><div class="line">    MyHttpResponse *myResponse = [MyHttpResponse mj_objectWithKeyValues:response.rawData]; <span class="comment">// 项目需要的response</span></div><div class="line">    myResponse.rawData = response.rawData;</div><div class="line">    myResponse.error = response.error;</div><div class="line">    <span class="keyword">return</span> [RACSignal <span class="keyword">return</span>:RACTuplePack(tuple.first, myResponse)];</div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<p><strong>调用：</strong></p>
<p>经过上面的<code>setupResponseSignalWithFlattenMapBlock:</code>方法设置后，信号返回的 RACTuple 的 second 为自定义的 response 对象。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">[DKNetworkManager.post(url).executeSignal subscribeNext:^(RACTuple *x) &#123;</div><div class="line"><span class="comment">//        DKNetworkResponse *response = x.second;</span></div><div class="line">    MyHttpResponse *myResponse = x.second;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125; error:^(<span class="built_in">NSError</span> *error) &#123;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<h4 id="取消请求"><a href="#取消请求" class="headerlink" title="取消请求"></a>取消请求</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 取消所有HTTP请求</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)cancelAllRequest;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> 取消指定URL的HTTP请求</div><div class="line"> */</div><div class="line">+ (<span class="keyword">void</span>)cancelRequestWithURL:(<span class="built_in">NSString</span> *)URL;</div></pre></td></tr></table></figure>
<h4 id="上传"><a href="#上传" class="headerlink" title="上传"></a>上传</h4><h5 id="上传文件"><a href="#上传文件" class="headerlink" title="上传文件"></a>上传文件</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 上传文件</div><div class="line"></div><div class="line"> @param URL 请求地址</div><div class="line"> @param parameters 请求参数</div><div class="line"> @param name 文件对应服务器上的字段</div><div class="line"> @param filePath 文件本地的沙盒路径</div><div class="line"> @param progressBlock 上传进度回调</div><div class="line"> @param callback 请求回调</div><div class="line"> @return 返回的对象可取消请求,调用cancel方法</div><div class="line"> */</div><div class="line">+ (<span class="built_in">NSURLSessionTask</span> *)uploadFileWithURL:(<span class="built_in">NSString</span> *)URL</div><div class="line">                             parameters:(<span class="built_in">NSDictionary</span> *)parameters</div><div class="line">                                   name:(<span class="built_in">NSString</span> *)name</div><div class="line">                               filePath:(<span class="built_in">NSString</span> *)filePath</div><div class="line">                          progressBlock:(DKNetworkProgressBlock)progressBlock</div><div class="line">                               callback:(<span class="keyword">void</span>(^)(DKNetworkResponse *response))callback;</div></pre></td></tr></table></figure>
<h5 id="上传图片"><a href="#上传图片" class="headerlink" title="上传图片"></a>上传图片</h5><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 上传图片</div><div class="line"></div><div class="line"> @param URL 请求地址</div><div class="line"> @param parameters 请求参数</div><div class="line"> @param name 图片对应服务器上的字段</div><div class="line"> @param images 图片数组</div><div class="line"> @param fileNames 图片文件名数组，传入nil时数组内的文件名默认为当前日期时间戳+索引</div><div class="line"> @param imageScale 图片文件压缩比 范围 (0.f ~ 1.f)</div><div class="line"> @param imageType 图片文件的类型，例:png、jpg(默认类型)....</div><div class="line"> @param progressBlock 上传进度回调</div><div class="line"> @param callback 请求回调</div><div class="line"> @return 返回的对象可取消请求,调用cancel方法</div><div class="line"> */</div><div class="line">+ (<span class="built_in">NSURLSessionTask</span> *)uploadImagesWithURL:(<span class="built_in">NSString</span> *)URL</div><div class="line">                               parameters:(<span class="built_in">NSDictionary</span> *)parameters</div><div class="line">                                     name:(<span class="built_in">NSString</span> *)name</div><div class="line">                                   images:(<span class="built_in">NSArray</span>&lt;<span class="built_in">UIImage</span> *&gt; *)images</div><div class="line">                                fileNames:(<span class="built_in">NSArray</span>&lt;<span class="built_in">NSString</span> *&gt; *)fileNames</div><div class="line">                               imageScale:(<span class="built_in">CGFloat</span>)imageScale</div><div class="line">                                imageType:(<span class="built_in">NSString</span> *)imageType</div><div class="line">                            progressBlock:(DKNetworkProgressBlock)progressBlock</div><div class="line">                                 callback:(<span class="keyword">void</span>(^)(DKNetworkResponse *response))callback;</div></pre></td></tr></table></figure>
<h4 id="下载"><a href="#下载" class="headerlink" title="下载"></a>下载</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> 下载文件</div><div class="line"></div><div class="line"> @param URL 请求地址</div><div class="line"> @param fileDir 文件存储目录(默认存储目录为Download)</div><div class="line"> @param progressBlock 文件下载的进度回调</div><div class="line"> @param callback 请求回调，filePath为文件保存路径</div><div class="line"> @return 返回 NSURLSessionDownloadTask 实例，可用于暂停继续，暂停调用 suspend 方法，开始下载调用 resume 方法</div><div class="line"> */</div><div class="line">+ (<span class="built_in">NSURLSessionTask</span> *)downloadWithURL:(<span class="built_in">NSString</span> *)URL</div><div class="line">                              fileDir:(<span class="built_in">NSString</span> *)fileDir</div><div class="line">                        progressBlock:(DKNetworkProgressBlock)progressBlock</div><div class="line">                             callback:(<span class="keyword">void</span>(^)(<span class="built_in">NSString</span> *filePath, <span class="built_in">NSError</span> *error))callback;</div></pre></td></tr></table></figure>
<h2 id="TODO"><a href="#TODO" class="headerlink" title="TODO"></a>TODO</h2><ul>
<li><p>链式编程虽然好看一点，但是没有常规调用方便，不能像以往一样敲两个字母 Xcode 就智能补全整个方法，并且可能会出现 <code>.get().post().get().post()</code> 这种没有意义的链式调用的情况。</p>
</li>
<li><p>用面向协议（接口）的函数式编程可以解决上面的问题，但是网络层工具的调用是可以没有顺序的，比如 <code>.params().post()</code> 跟 <code>.post().params()</code> 应该是都可以的，这样的话会让协议很难制定，还是会出现上面的问题。</p>
</li>
<li><p>日志保存文件</p>
</li>
<li><p>考虑添加 UI 层分类，让网络请求的错误日志以一种更友好的方式展示。</p>
</li>
<li><p>与服务端的通讯加密，考虑添加 RSA 非对称加密等方法。</p>
</li>
</ul>
<h2 id="后话"><a href="#后话" class="headerlink" title="后话"></a>后话</h2><p>DKNetworking 框架源码已经托管在 <a href="https://github.com/bingozb/DKNetworking/" target="_blank" rel="external">GitHub</a>，遵循 MIT 协议。欢迎向我们发起 PR 贡献您的代码，或者有什么建议欢迎 Issues。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong>本文作者：</strong>
      Bingo
    </li>
    <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://bingozb.github.io/35.html" title="DKNetworking 网络层框架">https://bingozb.github.io/35.html</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明： </strong>
      本博客所有文章除特别声明外，均采用 MIT 许可协议。转载请注明出处！
    </li>
  </ul>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/36.html" rel="next" title="JavaWeb 基于Maven+SSM 提供API服务">
                <i class="fa fa-chevron-left"></i> JavaWeb 基于Maven+SSM 提供API服务
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/34.html" rel="prev" title="解决 Pod include of non-modular header inside framework module 错误">
                解决 Pod include of non-modular header inside framework module 错误 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Bingo" />
          <p class="site-author-name" itemprop="name">Bingo</p>
           
              <p class="site-description motion-element" itemprop="description">He who hesitates is lost.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bingozb" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://coding.net/u/bingozb" target="_blank" title="Coding">
                  
                    <i class="fa fa-fw fa-git"></i>
                  
                  Coding
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/bingo_v587" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.facebook.com/profile.php?id=100013406670597" target="_blank" title="Facebook">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  Facebook
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#特点"><span class="nav-number">2.</span> <span class="nav-text">特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">3.</span> <span class="nav-text">安装</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#支持-Cocoapods-安装"><span class="nav-number">3.1.</span> <span class="nav-text">支持 Cocoapods 安装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#或者下载-Demo-项目"><span class="nav-number">3.2.</span> <span class="nav-text">或者下载 Demo 项目</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用"><span class="nav-number">4.</span> <span class="nav-text">使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#获取单例对象"><span class="nav-number">4.1.</span> <span class="nav-text">获取单例对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DKN-配置"><span class="nav-number">4.2.</span> <span class="nav-text">DKN 配置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#设置请求根路径"><span class="nav-number">4.2.1.</span> <span class="nav-text">设置请求根路径</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设置日志"><span class="nav-number">4.2.2.</span> <span class="nav-text">设置日志</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#开启日志打印"><span class="nav-number">4.2.2.1.</span> <span class="nav-text">开启日志打印</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#关闭日志打印"><span class="nav-number">4.2.2.2.</span> <span class="nav-text">关闭日志打印</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设置缓存"><span class="nav-number">4.2.3.</span> <span class="nav-text">设置缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#设置缓存方式"><span class="nav-number">4.2.3.1.</span> <span class="nav-text">设置缓存方式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#获取缓存大小"><span class="nav-number">4.2.3.2.</span> <span class="nav-text">获取缓存大小</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#清除缓存"><span class="nav-number">4.2.3.3.</span> <span class="nav-text">清除缓存</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设置序列化格式"><span class="nav-number">4.2.4.</span> <span class="nav-text">设置序列化格式</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#设置请求序列化格式"><span class="nav-number">4.2.4.1.</span> <span class="nav-text">设置请求序列化格式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#设置响应反序列化格式"><span class="nav-number">4.2.4.2.</span> <span class="nav-text">设置响应反序列化格式</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设置请求超时时间"><span class="nav-number">4.2.5.</span> <span class="nav-text">设置请求超时时间</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设置-Header"><span class="nav-number">4.2.6.</span> <span class="nav-text">设置 Header</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#设置一对请求头参数"><span class="nav-number">4.2.6.1.</span> <span class="nav-text">设置一对请求头参数</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#设置多对请求头参数"><span class="nav-number">4.2.6.2.</span> <span class="nav-text">设置多对请求头参数</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#网络状态"><span class="nav-number">4.3.</span> <span class="nav-text">网络状态</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#监听网络状态"><span class="nav-number">4.3.1.</span> <span class="nav-text">监听网络状态</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取当前网络状态"><span class="nav-number">4.3.2.</span> <span class="nav-text">获取当前网络状态</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#网络请求"><span class="nav-number">4.4.</span> <span class="nav-text">网络请求</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#常规调用"><span class="nav-number">4.4.1.</span> <span class="nav-text">常规调用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#链式调用"><span class="nav-number">4.4.2.</span> <span class="nav-text">链式调用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RAC-链式调用"><span class="nav-number">4.4.3.</span> <span class="nav-text">RAC 链式调用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RAC-链式调用-自定义信号的返回值"><span class="nav-number">4.4.4.</span> <span class="nav-text">RAC 链式调用 自定义信号的返回值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#取消请求"><span class="nav-number">4.4.5.</span> <span class="nav-text">取消请求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#上传"><span class="nav-number">4.4.6.</span> <span class="nav-text">上传</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#上传文件"><span class="nav-number">4.4.6.1.</span> <span class="nav-text">上传文件</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#上传图片"><span class="nav-number">4.4.6.2.</span> <span class="nav-text">上传图片</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#下载"><span class="nav-number">4.4.7.</span> <span class="nav-text">下载</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#TODO"><span class="nav-number">5.</span> <span class="nav-text">TODO</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后话"><span class="nav-number">6.</span> <span class="nav-text">后话</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  Copyright © 
  <span itemprop="copyrightYear">2017
  </span>
  <span class="author" itemprop="copyrightHolder">Bingo
  </span>
  All rights reserved.
</div>
        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytcdzpa3';
      var conf = 'c0c6117021d1cea9f11629100efd8446';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (search_path.endsWith("json")) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      $('#local-search-input').focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("A9MeTkIR49W9kOOSvkggsXge-gzGzoHsz", "HaIEOSDyxpcjwOjRjCYxiWjA");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
